package com.cci.kangdao.service.impl;

import com.cci.kangdao.crmapi.CRMHttpClientUtil;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.service.CSURemoteUpgradeService;
import com.cci.kangdao.utilTool.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



@Service("CSURemoteUpgradeService")
public class CSURemoteUpgradeServiceImpl implements CSURemoteUpgradeService {

    @Autowired
    private CustomerEngineRelDao customerEngineRelDao;

    @Override
    public ModelAndView getVehicleUpgradeStatus(Map<String, Object> map) {

        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");


        try {

            /**
             * 获取CSU远程升级车辆升级历史数据，并返回给APP
             */
            this.getCSUServiceData(request,response,CRMServiceConst.CSU_GET_VEHICLEUPGRADESSTATUS);


        }catch (Exception ex){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", -99);//自定义http code
            jsonObject.put("msg", ex.getMessage());
            ParameterTool.writeResponse(response, jsonObject.toString());

        }
        return null;
    }

    @Override
    public ModelAndView getUpgradeHistory(Map<String, Object> map) {

        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");


        try {

            /**
             * 获取CSU远程升级车辆升级历史数据，并返回给APP
             */
            this.getCSUServiceData(request,response,CRMServiceConst.CSU_GET_UPGRADEHISTORY);
            return null;

        }catch (Exception ex){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", -99);//自定义http code
            jsonObject.put("msg", ex.getMessage());
            ParameterTool.writeResponse(response, jsonObject.toString());

        }

        return null;
    }

    @Override
    public ModelAndView getTotalNeedUpgradeVehicles(Map<String, Object> map) {

        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");

        try {

            /**
             * 获取CSU远程升级车辆升级历史数据，并返回给APP
             */
            this.getCSUServiceData(request,response,CRMServiceConst.APP_GET_TOTALVEHICLES);

        }catch (Exception ex){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", -99);//自定义http code
            jsonObject.put("msg", ex.getMessage());
            ParameterTool.writeResponse(response, jsonObject.toString());

        }

        return null;
    }

    /**
     * http调取DBU接口服务
     * @param request
     * @param response
     * @param serviceName
     */
    private void  getCSUServiceData(HttpServletRequest request,HttpServletResponse response,String serviceName){

        /**
         * 1、查询用户信息
         */
        String userid = request.getHeader("userid");
        userid = AESTool.decryptString(userid);//解密userid

        /**
         * 2、根据用户信息，查询绑定的车辆ESN列表信息
         */
        List<String> userEsns = new ArrayList<>();
        if (serviceName.equals(CRMServiceConst.CSU_GET_UPGRADEHISTORY)){
            userEsns = customerEngineRelDao.getESNListByUserIdWithoutFlag(Long.parseLong(userid));
        }else
        {
            userEsns = customerEngineRelDao.getESNListByUserId(Long.parseLong(userid));
        }
        String esnListString = StringUtils.join(userEsns.toArray(), ",");// 以逗号分割

        /**
         * 3、根据用户信息，查询绑定的车辆信息
         */
        List<Map<String,Object>> esnModelsList = new ArrayList<>();
        if (serviceName.equals(CRMServiceConst.CSU_GET_UPGRADEHISTORY)){
            esnModelsList = customerEngineRelDao.getESNModelListByUserIdWithoutFlag(Long.parseLong(userid));
        }else
        {
            esnModelsList = customerEngineRelDao.getESNModelListByUserId(Long.parseLong(userid));
        }
        Map<String,Object> equipmentNoMap = new HashedMap();
        if (esnModelsList == null || esnModelsList.size() == 0){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", 0);//自定义http code
            jsonObject.put("msg", "暂无绑定车辆信息");
            jsonObject.put("data",new JSONObject());
            ParameterTool.writeResponse(response, jsonObject.toString());
            return ;
        }

        /**
         * 4、将esn和equipmentNO放入map，esn为key，equipmentNO为value
         */
        for (int i = 0; i < esnModelsList.size(); i++) {
            Map<String,Object> esnModelMap = esnModelsList.get(i);
            equipmentNoMap.put(esnModelMap.get("ESN").toString(), this.convertPlaintextToCiphertext(MapUtils.getString(esnModelMap,"equipmentNo","")));
        }

        String wwid = PropertiesUtil.getProperties("projectconfig.properties", "csu.wwid").trim();
        String token = PropertiesUtil.getProperties("projectconfig.properties", "csu.token").trim();

        /**
         * 请求头参数
         */
        Map<String,Object> headerMap = new HashedMap();
        headerMap.put("wwid",wwid);
        headerMap.put("token",token);
        headerMap.put("Content-Type","CCI");

        String serverUrl = PropertiesUtil.getProperties("projectconfig.properties", "csu.upgrade.host").trim();
        if (serviceName.equals(CRMServiceConst.APP_GET_TOTALVEHICLES)){
            serverUrl = serverUrl + CRMServiceConst.CSU_GET_VEHICLEUPGRADESSTATUS;
        }else
        {
            serverUrl = serverUrl + serviceName;
        }

        /**
         * get 请求参数
         */
        Map<String,Object> requestParamMap = new HashedMap();
        requestParamMap.put("esnList",esnListString);

        /**
         * 发起网络请求
         */

        JSONObject responseObject = CRMHttpClientUtil.httpPOSTRequest(serverUrl,headerMap,requestParamMap);
        JSONObject responseData = responseObject.getJSONObject("data");


        /**
         * 获取升级历史列表接口，需要添加升级历史总次数
         */
        if (serviceName.equals(CRMServiceConst.CSU_GET_UPGRADEHISTORY)){
            responseData.put("vehicleHistoryNums",0);
        }
        if (responseData != null && !responseData.isEmpty()){
            JSONArray vehicleHistoriesArr = responseData.getJSONArray("vehicles");
            if (vehicleHistoriesArr != null && !vehicleHistoriesArr.isEmpty()){

                if (serviceName.equals(CRMServiceConst.CSU_GET_UPGRADEHISTORY)){ // 获取升级历史列表接口
                    responseData.put("vehicleHistoryNums",responseData.getJSONArray("vehicles").size());
                }
                if (serviceName.equals(CRMServiceConst.APP_GET_TOTALVEHICLES)){ // 获取升级提醒数量接口
                    JSONObject jsonData = new JSONObject();
                    jsonData.put("totalVehicles",responseData.getJSONArray("vehicles").size());
                    responseData.put("status",0);
                    responseData.put("msg","");
                    responseData.put("data",jsonData);

                    //返回客户
                    ParameterTool.writeResponse(response, responseData.toString());
                    return;
                }
                /**
                 * 给每次升级历史添加设备号字段
                 */
                for (int j = 0; j < vehicleHistoriesArr.size(); j++) {
                    JSONObject vehicleJson = (JSONObject) vehicleHistoriesArr.get(j);
                    vehicleJson.put("equipmentNo",equipmentNoMap.get(vehicleJson.get("ESN").toString()));
                }
            }

        }
        // 返回客户
        if (serviceName.equals(CRMServiceConst.CSU_GET_UPGRADEHISTORY)){// 获取升级历史列表接口

            ParameterTool.writeResponse(response, responseObject.toString());

        }else if (serviceName.equals(CRMServiceConst.APP_GET_TOTALVEHICLES)){// 获取升级提醒数量接口
            JSONObject jsonData = new JSONObject();
            jsonData.put("totalVehicles",0);
            responseData.put("status",0);
            responseData.put("msg","");
            responseData.put("data",jsonData);

            ParameterTool.writeResponse(response, responseData.toString());
        }else if (serviceName.equals(CRMServiceConst.CSU_GET_VEHICLEUPGRADESSTATUS)){// 获取待升级列表接口

            ParameterTool.writeResponse(response, responseObject.toString());

        }

    }


    /**
     * 转化明文为**密文
     * @param plaintext
     * @return
     */
    private String convertPlaintextToCiphertext(String plaintext){

        if (plaintext == null||plaintext.isEmpty()){
            return "";
        }else if (plaintext.length() == 1){
            return plaintext;
        }else if (plaintext.length() == 2){
            StringBuffer buffer = new StringBuffer(plaintext);
            System.out.println(buffer.toString());//输出123456
            buffer.replace(plaintext.length()-1, plaintext.length(), "*");
            System.out.println(buffer.toString());//输出a23456

            return buffer.toString();
        }else if (plaintext.length() == 3){
            StringBuffer buffer = new StringBuffer(plaintext);
            buffer.replace(plaintext.length()-2, plaintext.length(), "**");
            System.out.println(buffer.toString());//输出a23456
            return buffer.toString();
        }else if (plaintext.length() == 4){
            StringBuffer buffer = new StringBuffer(plaintext);
            buffer.replace(plaintext.length()-3, plaintext.length()-1, "**");
            System.out.println(buffer.toString());//输出a23456
            return buffer.toString();
        }else if (plaintext.length() == 5){
            StringBuffer buffer = new StringBuffer(plaintext);
            buffer.replace((int) Math.ceil(plaintext.length()/2.0)-1, (int)Math.ceil(plaintext.length()/2.0)+1, "**");
            System.out.println(buffer.toString());//输出a23456
            return buffer.toString();
        }else if (plaintext.length() == 6){
            StringBuffer buffer = new StringBuffer(plaintext);
            buffer.replace((int) Math.ceil(plaintext.length()/2.0)-1, (int)Math.ceil(plaintext.length()/2.0)+1, "**");
            System.out.println(buffer.toString());//输出a23456
            return buffer.toString();
        }else if (plaintext.length() >= 7){
            StringBuffer buffer1 = new StringBuffer(plaintext);
            buffer1.replace((int) Math.ceil(plaintext.length()/2.0)-1, (int)Math.ceil(plaintext.length()/2.0)+1, "**");
            System.out.println(buffer1.toString());//输出a23456
            return buffer1.toString();
        }
        return plaintext;
    }
}
